package com.cjk.console.ctrl;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;

import javax.servlet.http.HttpSession;

import org.apache.commons.io.FileUtils;
import org.apache.commons.io.FilenameUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.InputStreamResource;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.cjk.console.SessionApi;
import com.cjk.console.service.FileService;
import com.cjk.foundation.commons.response.Response;
import com.cjk.foundation.request.WebUploadRequest;

@Controller
@RequestMapping("/")
public class FileController {
	
	@Autowired
	private FileService fileService;
	
	@RequestMapping(value = "/upload.do", method = RequestMethod.POST)
	@ResponseBody
	public Response upload(WebUploadRequest request, HttpSession session) {
		final Integer userId = SessionApi.getLoginUserId(session);
		return fileService.upload(request, userId);
	}
	
	@RequestMapping(value = "/image/{groupId}/{type}/{fileName:.+}", method = RequestMethod.GET)
	public ResponseEntity<InputStreamResource> image(@PathVariable("groupId") Integer groupId, @PathVariable("type") String type, @PathVariable("fileName") String fileName, HttpSession session) {
		final Integer userId = SessionApi.getLoginUserId(session);
		final String dir = "/easyTv/data/user_" + userId + "/group_" + groupId + "/zip/" + type + "/";
		
		File file = new File(dir, fileName);
		InputStream pictureData = null;
		try {
			pictureData = new FileInputStream(file);
		} catch (FileNotFoundException e1) {
			return new ResponseEntity<>(HttpStatus.NOT_FOUND);
		}
		InputStreamResource resource = new InputStreamResource(pictureData);

		String extention = FilenameUtils.getExtension(fileName);
		String mediaTypeValue = MediaType.APPLICATION_OCTET_STREAM_VALUE;

		if (StringUtils.isNotBlank(extention)) {
			mediaTypeValue = "image/" + extention;
		}

		HttpHeaders headers = new HttpHeaders();
		headers.setContentType(MediaType.valueOf(mediaTypeValue));
		try {
			headers.setContentLength(pictureData.available());
		} catch (IOException e) {
		}

		return new ResponseEntity<>(resource, headers, HttpStatus.OK);
	}
	
	@RequestMapping(value = "/device/{sn}/{fileName:.+}", method = RequestMethod.GET)
	public ResponseEntity<byte[]> downloadBySn(@PathVariable("sn") String sn, @PathVariable("fileName") String fileName) {
		final String dir = "/easyTv/data/" + sn;
		return download(dir, fileName);
	}
	
	@RequestMapping(value = "/group/{userId}/{groupId}/{fileName:.+}", method = RequestMethod.GET)
	public ResponseEntity<byte[]> downloadByGroup(@PathVariable("userId") Integer userId, @PathVariable("groupId") Integer groupId, @PathVariable("fileName") String fileName) {
		final String dir = "/easyTv/data/user_" + userId + "/group_" + groupId;
		return download(dir, fileName);
	}
	
	private ResponseEntity<byte[]> download(String dir, String fileName) {
		File directory = new File(dir);
		File file = new File(directory.getAbsoluteFile(), fileName);
		byte[] a = null;
		try {
			a = FileUtils.readFileToByteArray(file);
		} catch (IOException e) {
			e.printStackTrace();
		}
		HttpHeaders headers = new HttpHeaders();
		headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
		headers.add("Content-Disposition", "attachment;filename=" + fileName);
		return new ResponseEntity<>(a, headers, HttpStatus.OK);
	}
}
